public class Philosopher implements Runnable {

    private Object right;

    private Object left;

    public Philosopher(Object right,Object left){
        this.right=right;
        this.left=left;
    }

    public void doAction(String action){
        System.out.println(Thread.currentThread().getName()+"号"+action);
        try {
            Thread.sleep((long) Math.random()*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            doAction("思考万物");
            synchronized (left) {
                doAction("拿起左手餐具");
                synchronized (right) {
                    doAction("拿起右手餐具");
                    doAction("吃饭");
                    doAction("放下右手餐具");
                }
                doAction("放下左手餐具");
            }
        }
    }

    public static void main(String[] args) {
        Philosopher[] philosophers=new Philosopher[5];
        Object[] kz=new Object[philosophers.length];
        for (int i = 0; i <kz.length ; i++) {
            kz[i]=new Object();
        }

        //我来改一改

        for (int i = 0; i <philosophers.length ; i++) {
            philosophers[i]=new Philosopher(kz[i],kz[(i+1)%kz.length]);
            new Thread(philosophers[i],i+1+"").start();
        }
    }
}
